<template>
  <view class="page">
    <view class="p-top">
      <text style="margin-right: 10rpx">支付剩余时间</text>
      <u-count-down :time="residue" format="HH:mm:ss" autoStart @finish="payEnd" />
    </view>
    <view class="p-body">
      <view class="p-price">
        <u-text
          :text="`￥${payMethod == 'wechat' ? price : virtual_coin + '币'}`"
          color="#000000"
          size="40rpx"
          align="center"
          bold
          line-height="100rpx"
        />
        <u-text
          :text="`${order_no || '-'}`"
          color="#979797"
          size="28rpx"
          align="center"
        />
      </view>
      <view class="p-row" v-for="(i, k) in payList" :key="k" @click="checkPay(i)">
        <u-image
          show-loading
          :show-menu-by-longpress="false"
          :src="i.icon"
          :width="i.width"
          :height="i.height"
        />
        <view class="r-flex">
          <u-text :text="i.name" color="#222" size="28rpx" line-height="50rpx" />
          <u-text :text="i.describe" color="#979797" size="24rpx" line-height="50rpx" />
        </view>
        <u-image
          :show-menu-by-longpress="false"
          :src="i.select ? checked : unCheck"
          width="32rpx"
          height="32rpx"
        />
      </view>
      <!-- <u-notice-bar
        text="每单只能使用一张优惠券"
        color="#EC9B51"
        speed="40"
        radius="14rpx"
        bg-color="#FFF5EC"
        font-size="28rpx"
      /> -->
    </view>
    <view class="btn">
      <view class="button" v-if="payMethod == 'wechat'" @click="confirm"
        >立即支付 ￥{{ price }}</view
      >
      <view class="button" v-else @click="confirm"
        >立即支付 ￥{{ virtual_coin }}币</view
      >
    </view>
  </view>
</template>

<script>
import { mallPayment } from "@/request/mallApi.js";
export default {
  data() {
    return {
      checked: require("@/static/mall/checked.png"),
      unCheck: require("@/static/mall/check.png"),
      residue: 0, // 支付倒计时
      expiretime: 0, // 支付倒计时上限
      order_id: "", // 订单ID
      price: "0.00", // 支付金额
      virtual_coin: "0", // 支付虚拟币
      token: "", // 订单token令牌
      order_type: "goods", // 订单类型
      order_no: "", // 订单号
      payList: [], // 支付方式
    };
  },
  onLoad(e) {
    this.token = e.token;
    let data = JSON.parse(e.data);
    this.init(data);
    this.initPay();
  },
  computed: {
    // 支付方式
    payMethod() {
      let payInfo = this.payList.find((i) => i.select);
      return payInfo?.type;
    },
  },
  methods: {
    // 切换支付方式
    checkPay(v) {
      this.payList.forEach((i) => {
        i.select = i.type == v.type;
      });
    },
    // 初始化订单信息
    init(data) {
      var sum = 0,
        sumCoin = 0,
        order_ids = [];
      if (data.length <= 1) {
        this.price = data[0].price || 0;
        this.virtual_coin = data[0].virtual_coin || 0;
        this.order_type = data[0].type;
        this.order_no = `订单号：${data[0].order_no}`;
        this.order_id = data[0].order_id;
        this.expiretime = data[0].expiretime * 1000;
        this.residue = data[0].expiretime * 1000 - (Number(new Date()) + 1000);
      } else {
        data.forEach((item) => {
          sum = this.$bcadd(sum, item.price);
          sumCoin = this.$bcadd(sumCoin, item.virtual_coin);
          order_ids.push(item.order_id);
        });
        this.price = sum || 0;
        this.virtual_coin = sumCoin || 0;
        this.order_no = "合并支付 " + data.length + "个订单";
        this.order_id = order_ids;
        this.expiretime = data[0].expiretime * 1000;
        this.residue = data[0].expiretime * 1000 - (Number(new Date()) + 1000);
      }
    },
    // 加载支付方式
    initPay() {
      let userInfo = this.$getStorage("USER_INFO");
      let list = [
        {
          icon: require("@/static/mall/payweChat.png"),
          name: "微信支付",
          type: "wechat",
          method: "miniapp",
          describe: "推荐安装微信5.0及以上的版本使用",
          select: true,
          width: "78rpx",
          height: "64rpx",
        },
      ];
      // 后续待开通
      // if (userInfo.isPlus) {
      //   list.push({
      //     icon: require("@/static/mall/payCoin.png"),
      //     name: "余额支付",
      //     type: "balance",
      //     method: "balance",
      //     describe: "会员账户余额支付",
      //     select: false,
      //     width: "78rpx",
      //     height: "78rpx",
      //   });
      // }
      if (userInfo.isPlus) {
        list.push({
          icon: require("@/static/mall/payCoin.png"),
          name: "虚拟币支付",
          type: "virtual",
          method: "virtual",
          describe: "会员账户虚拟币支付",
          select: false,
          width: "78rpx",
          height: "78rpx",
        });
      }
      this.payList = list;
    },
    // 确认支付
    confirm() {
      let payInfo = this.payList.find((i) => i.select);
      if (payInfo.type != "virtual") {
        // 非虚拟币支付
        uni.login({
          success: (e) => {
            uni.showLoading({
              title: "处理中",
              mask: true,
            });
            let data = {
              type: payInfo.type,
              method: payInfo.method,
              code: e.code,
              order_type: this.order_type,
              order_id: this.order_id,
              token: this.token,
            };
            mallPayment(data)
              .then((res) => {
                if (res.code == 1) {
                  if (payInfo.type == "wechat") {
                    let pay = res.data.data;
                    uni.requestPayment({
                      appId: pay.appId,
                      nonceStr: pay.nonceStr,
                      package: pay.package,
                      paySign: pay.paySign,
                      signType: pay.signType,
                      timeStamp: pay.timeStamp,
                      success: () => {
                        setTimeout(() => {
                          uni.redirectTo({
                            url: `/pages/mall/payed?id=${this.order_id.toString()}&type=${
                              res.data.type
                            }`,
                          });
                        }, 1500);
                      }
                    });
                  } else {
                    uni.showToast({
                      title: "支付成功",
                      icon: "success",
                      success: () => {
                        setTimeout(() => {
                          uni.redirectTo({
                            url: `/pages/mall/payed?id=${this.order_id}&type=${res.data.type}`,
                          });
                        }, 1500);
                      },
                    });
                  }
                }
              })
              .finally(() => {
                uni.hideLoading();
              });
          },
          fail: (e) => {
            uni.showModal({
              content: "无法获取微信code,原因为: " + e.errMsg,
              showCancel: false,
            });
          },
        });
      } else {
        let info = {
          expiretime: this.expiretime, // 支付倒计时
          order_id: this.order_id, // 订单ID
          virtual_coin: this.virtual_coin, // 支付虚拟币
          token: this.token, // 订单token令牌
          order_type: this.order_type, // 订单类型
          order_no: this.order_no, // 订单号
        };
        uni.redirectTo({
          url: `/pages/mall/cashierCoin?info=${JSON.stringify(info)}`,
        });
      }
    },
    // 结束支付
    payEnd() {
      uni.showToast({
        title: "支付超时，订单已取消",
        icon: "none",
        mask: true,
        success: () => {
          setTimeout(() => {
            uni.navigateBack({ delta: 1 });
          }, 1500);
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  .p-top {
    height: 88rpx;
    width: 100%;
    background-color: #cee7e5;
    display: flex;
    font-size: 32rpx;
    color: $active-color;
    align-items: center;
    justify-content: center;
  }
  /deep/.u-count-down__text {
    font-size: 32rpx;
    color: $active-color;
  }
  .p-body {
    padding: 20rpx;
    .p-price {
      height: 206rpx;
      border-bottom: 1rpx solid #d9d9d999;
      margin-bottom: 20rpx;
    }
    .p-row {
      display: flex;
      justify-content: start;
      align-items: center;
      padding: 20rpx;
      &:active {
        background-color: #f7ffff;
      }
      .r-flex {
        flex: 1;
        margin-left: 20rpx;
      }
    }
  }
  .btn {
    position: fixed;
    background-color: #fff;
    box-shadow: 0 0 8rpx rgba(0, 0, 0, 0.05);
    height: 126rpx;
    padding: 20rpx;
    bottom: 0;
    left: 0;
    right: 0;
    .button {
      width: 100%;
      height: 88rpx;
      text-align: center;
      line-height: 88rpx;
      color: $active-color;
      font-size: 28rpx;
      background-color: #cee7e5;
      border-radius: 100rpx;
      &:active {
        background-color: #b9e4e1;
      }
    }
  }
}
</style>
